import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/layout'
import Home from '@/views/layout/home'
import store from '@/store'
Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => err)
}
const routes = [
  {
    path: '/login',
    component: () => import('@/views/login')
  },
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '/',
        component: Home,
        // 元信息， 额外的参数
        meta: {
          isKeepAlive: true
        }
      },
      {
        path: '/question',
        component: () => import('@/views/layout/question')
      },
      {
        path: '/video',
        component: () => import('@/views/layout/video')
      },
      {
        path: '/user',
        component: () => import('@/views/layout/user')
      }
    ]
  },
  {
    path: '/user/edit',
    component: () => import('@/views/layout/user/edit')
  },
  {
    path: '/search',
    component: () => import('@/views/search')
  },
  {
    path: '/result',
    component: () => import('@/views/search/result')
  },
  {
    path: '/article/:id',
    component: () => import('@/views/article')
  },
  {
    path: '/user/chat',
    component: () => import('@/views/layout/user/chat')
  }
]

const router = new VueRouter({
  routes
})

// 只要导航发生跳转，都会先执行beforeEach的函数
// 守卫的思路
// 1. 判断是否有token  如果有 直接放行
// 2. 如果没有token,,判断去的页面是否需要登录
// 3. 如果去的页面不需要登录，放行
// 4. 如果去的页面需要登录，拦截到登录页面。
// 需要登录的页面
const privateURL = ['/user', '/user/edit']
router.beforeEach((to, from, next) => {
  const tokenInfo = store.state.user.tokenInfo
  if (tokenInfo.token) {
    return next()
  }
  // 没有token,但是这些页面不需要登录
  if (!privateURL.includes(to.path)) {
    return next()
  }
  // 需要登录，且没有token
  next({
    path: '/login',
    // 路由跳转时传递的参数
    query: {
      // 回跳
      back: to.fullPath
    }
  })
})

export default router
